package com.iemes.service.impl.work_process;

import java.util.List;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.iemes.entity.PodButtonFormMap;
import com.iemes.entity.PodFunctionFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.BaseExtMapper;
import com.iemes.service.work_process.PodButtonService;
import com.iemes.util.ListUtils;
import com.iemes.util.ShiroSecurityHelper;
import com.iemes.util.UUIDUtils;

@Service
public class PodButtonServiceImpl implements PodButtonService {
	
	private Logger log = Logger.getLogger(this.getClass());
			
	@Inject
	private BaseExtMapper baseMapper;

	@Override
	@Transactional
	public void savePodButton(PodButtonFormMap podButtonFormMap) throws BusinessException {
		try {
			String id = podButtonFormMap.getStr("id");
			String podButtonNo = podButtonFormMap.getStr("pod_button_no");
			
			if(StringUtils.isEmpty(podButtonNo)) {
				throw new BusinessException("POD按钮编号不能为空，请输入！");
			}
			
			PodButtonFormMap podButtonFormMap2 = new PodButtonFormMap();
			podButtonFormMap2.put("pod_button_no", podButtonNo);
			podButtonFormMap2.put("site_id", ShiroSecurityHelper.getSiteId());
			List<PodButtonFormMap> list = baseMapper.findByNames(podButtonFormMap2);
			
			//判断POD触发器是否正确
			List<PodFunctionFormMap> listPodFunctionFormMap = baseMapper.findByAttribute("id", podButtonFormMap.getStr("pod_function"), PodFunctionFormMap.class);
			if (!ListUtils.isNotNull(listPodFunctionFormMap)) {
				log.error("未检索到对应的触发器信息,请通过检索功能选择正确的触发器");
				throw new BusinessException("未检索到对应的触发器信息,请通过检索功能选择正确的触发器");
			}
			
			//如果编号存在，就执行更新，不存在就执行新增
			if (ListUtils.isNotNull(list)) {
				//更新 
				PodButtonFormMap podButtonFormMap3 = new PodButtonFormMap();
				podButtonFormMap3 = list.get(0);
				id = podButtonFormMap3.getStr("id");
				podButtonFormMap.set("id", id);
				
				baseMapper.editEntity(podButtonFormMap);
			}else {
				//新增
				podButtonFormMap.put("id", UUIDUtils.getUUID());
				baseMapper.addEntity(podButtonFormMap);
			}
			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("POD按钮保存失败！"+e.getMessage());
		}
	}

	@Override
	@Transactional
	public void delPodButton(String podButtonId) throws BusinessException {
		try {
			baseMapper.deleteByAttribute("id", podButtonId, PodButtonFormMap.class);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("POD按钮删除失败！"+e.getMessage());
		}
	}

}
